package com.itany.shop.filter;

import com.itany.shop.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石小俊
 * @date 2023年07月11日 11:26
 * 登录检查过滤器
 * 用户未登录时无法访问当前项目中除了登录注册相关的功能以及主页以外的功能
 * 如果用户未登录,且访问了其他功能,则直接跳转到登录页面提示:您尚未登录,请先登录
 * 只有当用户成功登录之后,才能访问所有功能
 */
@WebFilter("/*")
public class CheckLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取请求
        String path = request.getServletPath();
        // 遇到以下请求直接放行
        if(path.endsWith(".user") || "/jsp/login.jsp".equals(path) || "/jsp/register.jsp".equals(path) || "/jsp/main.jsp".equals(path) || "/index.jsp".equals(path) || "findAll.product".equals(path) || "/showCode".equals(path) || "/js/jquery-3.4.1.min.js".equals(path)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        // 如果是其他请求,则判断是否登录
        // 登录后在session中会存在user信息
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            // 如果没有取到user,说明用户尚未登录
            request.setAttribute("loginMsg","您尚未登录,请先登录");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }
        // 如果取到了user,说明已经登录,直接放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
